﻿
namespace System.Collections.Generic
{
    /// <summary>
    /// 集合扩展方法
    /// </summary>
    public static class ExIEnumerableT
    {
        /// <summary>
        /// 将一个大集合拆分为多个小集合
        /// </summary>
        /// <param name="source">原数据</param>
        /// <param name="intEachCount">每个集合大小</param>
        /// <param name="blnUseSameList">总返回同一个IList对象</param>
        /// <returns>小集合的yield迭代</returns>
        public static IEnumerable<IList<T>> ToSmallList<T>(
            this IEnumerable<T> source,
            int intEachCount,
            bool blnUseSameList = false)
        {
            if (source == null) yield break;
            IList<T> lstSmallList = new List<T>(intEachCount);
            if (blnUseSameList)
            {
                foreach (var item in source)
                {
                    lstSmallList.Add(item);
                    if (lstSmallList.Count == intEachCount)
                    {
                        yield return lstSmallList;
                        lstSmallList.Clear();
                    }
                }
            }
            else
            {
                foreach (var item in source)
                {
                    lstSmallList.Add(item);
                    if (lstSmallList.Count == intEachCount)
                    {
                        yield return lstSmallList;
                        lstSmallList = new List<T>(intEachCount);
                    }
                }
            }
            if (lstSmallList.Count > 0)
            {
                yield return lstSmallList;
            }
        }

        /// <summary>
        /// 将二级集合中的对象逐个返回
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source">原数据</param>
        /// <returns>逐个对象</returns>
        public static IEnumerable<T> GetEachItem<T>(
            this IEnumerable<IEnumerable<T>> source)
        {
            if (source == null) yield break;
            foreach (var item1 in source)
            {
                if (item1 == null) continue;
                foreach (var item2 in item1)
                {
                    yield return item2;
                }
            }
        }
    }
}
